<template>
  <view class="container">
    <view class="timer-circle">
      <text class="timer-text">{{ formattedTime }}</text>
    </view>
    <view class="button-container">
      <button class="btn-connect" @click="connectToBluetoothDevice">连接蓝牙设备</button>
      <button class="btn-start" @click="startTimer">启动</button>
      <button @click="stopTimer">停止</button>
    </view>
    <cover-view v-show="showMask" class="mask"></cover-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      timer: null,
      startTime: 0,
      formattedTime: '00:00:00.000',
      targetDevice: {
        names: ['ZNZX-TEST002', 'ZNZX-TEST001'],
        deviceId: ''
      },
      showMask: false,
      isConnected: false
    }
  },
  onLoad() {
    this.initializeEnvironment();
    this.checkBluetoothConnection();
    this.startInterval();
  },
  onUnload() {
    this.saveStartTime();
    clearInterval(this.timer);
  },
  methods: {
    initializeEnvironment() {
      this.startTime = uni.getStorageSync('startTime') || 0;
      if (this.startTime) this.updateFormattedTime();
      this.targetDevice.deviceId = uni.getStorageSync('deviceId') || '';
      this.isConnected = uni.getStorageSync('isConnected') === true;
    },
    saveStartTime() {
      uni.setStorageSync('startTime', this.startTime);
      uni.setStorageSync('isConnected', this.isConnected);
      uni.setStorageSync('deviceId', this.targetDevice.deviceId);
    },
    startInterval() {
      this.timer = setInterval(this.updateFormattedTime, 100);
    },
    connectToBluetoothDevice() {
      if (this.isConnected) {
        this.showConnectedMessage();
        return;
      }
      this.showMask = true;
      this.connectToBluetoothDeviceApp();
    },
    showConnectedMessage() {
      uni.showToast({
        title: '设备已连接',
        icon: 'none'
      });
    },
    connectToBluetoothDeviceApp() {
      uni.showLoading({
        title: '正在搜索并连接蓝牙',
        mask: true
      });
      uni.openBluetoothAdapter({
        success: this.startBluetoothDevicesDiscovery,
        fail: (err) => {
          uni.showToast({
            title: '蓝牙模块初始化失败',
            icon: 'none'
          });
          this.showMask = false;
          uni.hideLoading();
        }
      });
    },
    startBluetoothDevicesDiscovery() {
      uni.startBluetoothDevicesDiscovery({
        success: () => {
          uni.onBluetoothDeviceFound(this.handleBluetoothDeviceFound);
        },
        fail: (err) => {
          uni.showToast({
            title: '开始搜索蓝牙设备失败',
            icon: 'none'
          });
          this.showMask = false;
          uni.hideLoading();
        }
      });
    },
    handleBluetoothDeviceFound(res) {
      const device = res.devices.find(device => this.targetDevice.names.includes(device.name));
      if (device) {
        this.targetDevice.deviceId = device.deviceId;
        this.stopBluetoothDevicesDiscovery();
        this.connectToDevice();
      }
    },
    stopBluetoothDevicesDiscovery() {
      uni.stopBluetoothDevicesDiscovery({
        success: () => console.log('停止搜索蓝牙设备'),
        fail: (err) => console.error('停止搜索蓝牙设备失败', err)
      });
    },
    connectToDevice() {
      if (!this.targetDevice.deviceId) {
        uni.showToast({
          title: '未找到目标设备',
          icon: 'none'
        });
        this.showMask = false;
        uni.hideLoading();
        return;
      }
      uni.createBLEConnection({
        deviceId: this.targetDevice.deviceId,
        success: () => {
          this.isConnected = true;
          uni.showToast({
            title: '连接成功',
            icon: 'success'
          });
          this.saveDeviceId(this.targetDevice.deviceId);
          this.showMask = false;
          uni.hideLoading();
        },
        fail: (err) => {
          uni.showToast({
            title: `连接失败: ${err.errMsg}`,
            icon: 'none'
          });
          this.showMask = false;
          uni.hideLoading();
        }
      });
    },
    saveDeviceId(deviceId) {
      const savedDevices = uni.getStorageSync('savedDevices') || [];
      if (!savedDevices.includes(deviceId)) {
        savedDevices.push(deviceId);
        uni.setStorageSync('savedDevices', savedDevices);
      }
    },
    checkBluetoothConnection() {
      if (this.targetDevice.deviceId) {
        uni.getConnectedBluetoothDevices({
          services: ['battery_service'],
          success: (res) => {
            if (res.devices.find(device => device.deviceId === this.targetDevice.deviceId)) {
              this.isConnected = true;
              this.showConnectedMessage();
            } else {
              this.connectToBluetoothDevice();
            }
          },
          fail: this.connectToBluetoothDevice
        });
      } else {
        this.connectToBluetoothDevice();
      }
    },
    updateFormattedTime() {
      if (this.startTime) {
        const elapsed = Date.now() - this.startTime;
        this.formattedTime = this.formatTime(elapsed);
      }
    },
    formatTime(milliseconds) {
      const totalSeconds = Math.floor(milliseconds / 1000);
      const h = Math.floor(totalSeconds / 3600);
      const m = Math.floor((totalSeconds % 3600) / 60);
      const s = totalSeconds % 60;
      const ms = milliseconds % 1000;
      return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}:${ms.toString().padStart(3, '0')}`;
    },
    startTimer() {
      if (!this.isConnected) {
        this.connectToBluetoothDevice();
        return;
      }
      if (!this.startTime) {
        this.startTime = Date.now();
        this.saveStartTime();
      }
    },
    stopTimer() {
      if (this.startTime) {
        uni.showModal({
          title: '确认停止',
          content: '是否确定要停止计时？',
          success: (res) => {
            if (res.confirm) {
              clearInterval(this.timer);
              const finalTime = this.formattedTime;
              this.resetTimer(finalTime);
            }
          }
        });
      }
    },
    resetTimer(finalTime) {
      uni.setStorageSync('finalTime', finalTime);
      this.startTime = 0;
      this.formattedTime = '00:00:00.000';
      uni.removeStorageSync('startTime');
      uni.removeStorageSync('isConnected');
      uni.removeStorageSync('deviceId');
      uni.navigateBack({
        delta: 1
      });
    }
  }
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #fff;
}

.timer-circle {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.timer-text {
  font-size: 24px;
  font-weight: bold;
}

.button-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
}

button {
  width: 200px;
  margin: 10px 0;
  padding: 10px;
  font-size: 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.btn-start {
  background-color: #07C160;
  color: white;
}

.btn-connect {
  background-color: #007BFF;
  color: white;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(5px);
  z-index: 1000;
  transition: opacity 0.3s ease;
}
</style>
